<template>
  <div
    class="fty-box"
    style="
      padding: 20px 20px;
      height: 100%;
      width: 100%;
      position: absolute;
      top: 0px;
      background-color: #f9fbfd;
      overflow: auto;
    "
  >
    <el-page-header
      class="mb-3"
      :content="$t('menu.M_10688000')"
      @back="$emit('update:showUserView', false)"
    />

    <!-- body -->
    <el-card
      class="fty-card"
      shadow="never"
      :body-style="{ padding: '0px' }"
      @current-change="currentChangeHandle"
      :page-size="pageSize"
      :total="totalPage"
      :current-page="pageIndex"
    >
      <div class="search-box">
        <el-form class="p-4" inline @submit.prevent>
          <el-form-item>
            <el-input
              maxlength="64"
              v-model="condition"
              @blur="() => (condition = condition.trim())"
              :placeholder="$t('user.query_condition')"
              style="width: 300px"
              clearable
              @clear="fetchData"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="w-8" @click="fetchData((pageIndex = 1))">
              <svg-icon icon-class="search" />
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="isAuth('10688010.USER_MANAGE')"
              type="primary"
              class="w-8"
              @click="handleAdd"
            >
              <svg-icon icon-class="plus" />
            </el-button>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button style="border: none" type="primary" class="p-2" size="medium">
              <table-column-filter
                :list="settingList"
                :default-setting="defaultSettings"
                v-model:settings="settings"
                domain="user.manage"
              />
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :show-overflow-tooltip="true" v-loading="listLoading" :data="tableData">
        <!--        <el-table-column prop="username" align="left" width="70px">-->
        <!--          <template v-slot="{ row }">-->
        <!--            <div-->
        <!--              class="user-list-avatar"-->
        <!--            >-->
        <!--              <img-->
        <!--                :src="getLogo(row.logoUrl)"-->
        <!--              />-->
        <!--            </div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column :label="$t('user.username')" prop="username" align="center" />
        <el-table-column
          v-if="showHeader('characterCode')"
          key="characterCode"
          :label="$t('user.user_type')"
          prop="characterCode"
          align="center"
        />
        <el-table-column :label="$t('user.contact_name')" prop="name" align="center" />
        <el-table-column
          v-if="showHeader('orgName')"
          key="orgName"
          :label="$t('user.organization')"
          prop="orgName"
          align="center"
        />
        <el-table-column :label="$t('user.status')" prop="status" align="center">
          <template v-slot="{ row }">
            <el-tag type="warning" v-if="row.status === 0">{{ statusFilter(row.status) }}</el-tag>
            <el-tag type="success" v-if="row.status === 1">{{ statusFilter(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('creTime')"
          :label="$t('common.createTime')"
          key="creTime"
          prop="creTime"
          align="center"
        >
          <template v-slot="{ row }">
            <div :title="timeFilter(row.creTime) ">
              {{ dateFilter(row.creTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('lastLoginTime')"
          :label="$t('user.last_login_time')"
          key="lastLoginTime"
          prop="lastLoginTime"
          align="center"
        >
          <template v-slot="{ row }">
            <div :title="timeFilter(row.lastLoginTime)">
              {{ dateFilter(row.lastLoginTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="isAuth('10688010.USER_MANAGE') || isAuth('10688010.COUNTRY_CONFIG_MANAGE')"
          header-align="center"
          align="center"
          width="50"
        >
          <template v-slot="scope">
            <el-dropdown
              v-if="
                scope.row.username != loginUserName &&
                scope.row.managerFlag != 1 &&
                (isAuth('10688010.USER_MANAGE') || isAuth('10688010.COUNTRY_CONFIG_MANAGE'))
              "
              @command="handleClick"
            >
              <span class="el-dropdown-link">
                <svg-icon icon-class="MoreFilled" style="font-size: 20px" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="isAuth('10688010.USER_MANAGE')"
                    :command="beforeHandleCommand('edit', scope.row)"
                  >
                <svg-icon icon-class="outlined-edit" />
                    <span>{{ $t('common.modify') }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 1 && isAuth('10688010.USER_MANAGE')"
                    :command="beforeHandleCommand('lock', scope.row)"
                  >
                  <svg-icon icon-class="Lock" />

                    <span>{{ $t('user.lock') }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 0 && isAuth('10688010.USER_MANAGE')"
                    :command="beforeHandleCommand('unlock', scope.row)"
                  >
                <svg-icon icon-class="Unlock" />
                    <span>{{ $t('user.unlock') }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="isAuth('10688010.USER_MANAGE')"
                    :command="beforeHandleCommand('delete', scope.row)"
                  >
                  <svg-icon icon-class="Delete" />
                    <span>{{ $t('common.delete') }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="isAuth('10688010.COUNTRY_CONFIG_MANAGE')"
                    :command="beforeHandleCommand('manageCountry', scope.row)"
                  >
                    <svg-icon
                      icon-class="outlined-global"
                    ></svg-icon>
                    <span>{{ $t('common.manage_country_config') }}</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <user-add
      ref="userDialog"
      :type="operationType"
      :user-id="editUserId"
      @submit="fetchData"
      v-model="addUserVisible"
      :title="editUserId ? $t('user.edit_user_title') : $t('user.add_user_title')"
    ></user-add>
    <manage-country
      v-model="manageCountryVisible"
      ref="manageCountry"
    ></manage-country>
  </div>
</template>

<script>
import TableColumnFilter from '@/components/page-setting/table-column-filter'

import { deleteUser, getUserPage, lockUser, unlockUser } from '@/api/user'
import { timeFilter, dateFilter } from '@/filters/index'
import UserAdd from '@/views/system/permission/components/user-add'
import ManageCountry from './components/manage-country'
import { isAuth } from '@/utils'
export default {
  props: {
    showUserView: {
      type: Boolean
    }
  },
  components: {
    UserAdd,
    TableColumnFilter,
    ManageCountry
  },
  data() {
    return {
      settings: {
        conditions: [],
        columns: []
      },
      loginUserName: '',
      tableData: [],
      listLoading: false,
      selectedData: [],
      paginationShow: true,
      condition: '',
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      operationType: '',
      editUserId: '',
      addUserVisible: false,
      manageCountryVisible: false
    }
  },
  mounted() {
    const userInfo = JSON.parse(localStorage.getItem(this.$store.getters.keys.storage.username))
    this.loginUserName = userInfo.username
    this.$watch('showUserView', (next, origin) => {
      console.log(next)
      if (next) {
        this.fetchData()
      }
    })
  },
  computed: {
    settingList() {
      return {
        columns: [
          {
            title: this.$t('user.user_type'),
            code: 'characterCode'
          },
          {
            title: this.$t('user.organization'),
            code: 'orgName'
          },
          {
            title: this.$t('common.createTime'),
            code: 'creTime'
          },
          {
            title: this.$t('user.last_login_time'),
            code: 'lastLoginTime'
          }
        ]
      }
    },
    defaultSettings() {
      return {
        columns: [
          'lastLoginTime'
          // this.$t('common.online'),
        ]
      }
    }
  },
  methods: {
    statusFilter(status) {
      const statusMap = {
        0: 'Locked',
        1: 'Valid'
      }
      return statusMap[status]
    },
    timeFilter,
    dateFilter,
    isAuth,
    showHeader(label) {
      var list = this.settings['columns']
      return list ? list.includes(label) : false
    },
    showFormItem(label) {
      var list = this.settings['conditions']
      return list ? list.includes(label) : false
    },
    fetchData() {
      this.editUserId = ''
      this.listLoading = true
      getUserPage({
        pageNo: this.pageIndex,
        pageSize: this.pageSize,
        status: '',
        condition: this.condition,
        platCode: 'PASS'
      })
        .then((res) => {
          this.listLoading = false
          this.tableData = res.data
          this.totalPage = res.rows
        })
        .catch((e) => {
          this.$confirmError(e)
          this.listLoading = false
        })
    },
    showModify(row) {
      var username = this.$store.state.user.name
      if (username === row.username) {
        return false
      }
      return row.userId !== 1
    },
    showLock(row) {
      var username = this.$store.state.user.name
      if (username === row.username) {
        return false
      }
      return row.status === 1 && row.userId !== 1
    },
    showUnLock(row) {
      var username = this.$store.state.user.name
      if (username === row.username) {
        return false
      }
      return row.status === 0 && row.userId !== 1
    },
    handleLock(row) {
      this.$confirm(this.$t('user.sure_to_lock_user') + `[${row.email}]?`, this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        lockUser(row.userId)
          .then((res) => {
            this.$message({
              message: this.$t('user.lock_success'),
              type: 'success'
            })
            this.fetchData()
          })
          .catch(this.$confirmError)
      })
    },
    handleUnlock(row) {
      this.$confirm(
        this.$t('user.sure_to_unlock_user') + `[${row.email}]?`,
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        unlockUser(row.userId)
          .then((res) => {
            this.$message({
              message: this.$t('user.unlock_success'),
              type: 'success'
            })
            this.fetchData()
          })
          .catch(this.$confirmError)
      })
    },
    handleClick(val) {
      let command = val.command
      let row = val.row
      if (command === 'edit') {
        this.handleEdit(row)
      } else if (command === 'lock') {
        this.handleLock(row)
      } else if (command === 'unlock') {
        this.handleUnlock(row)
      } else if (command === 'delete') {
        this.handleDelete(row)
      } else if (command === 'manageCountry') {
        this.showManageCountryDialog(row.userId)
      }
    },
    beforeHandleCommand(command, row) {
      return {
        row: row,
        command: command
      }
    },
    handleEdit(row) {
      this.operationType = 'Update'
      this.editUserId = row.userId
      this.addUserVisible = true
      this.$refs.userDialog.init(row.userId)
    },
    handleDelete(row) {
      this.$confirm(this.$t('user.delete_tip', { username: row.username }), '', {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        deleteUser(row.userId)
          .then((res) => {
            this.$message.success(this.$t('common.operate_success'))
            this.fetchData()
          })
          .catch((e) => {
            this.$confirmError(e)
          })
      })
    },
    handleAdd() {
      this.addUserVisible = true
      this.editUserId = ''
      this.$refs.userDialog.init('')
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.fetchData()
    },
    currentChangeHandle(val) {
      this.pageIndex = val
      this.fetchData()
    },
    showManageCountryDialog(userId) {
      this.manageCountryVisible = true
      this.$nextTick(() => {
        this.$refs.manageCountry.init(userId)
      })
    }
  }
}
</script>

<style lang="scss">
.terminal-list {
  .el-table .cell {
    /* height: 30px !important; */
  }
}
</style>

<style lang="scss" scoped>
.query-button {
  margin-left: 30px;
}
.user-list-avatar {
  width: 43.8px;
  height: 43.8px;
  border-radius: 60px;
  overflow: hidden;
  margin: 5px;
  img {
    margin-right: 5px;
    border-radius: 50%;
  }
}
.pagination-wrapper {
  text-align: right;
}
</style>
